package core;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import dto.Message;

public class SendMsg {

	Message msg = null;
	boolean validated = false;

	public void setMsg(Message msg) {
		this.msg = msg;

		String toIP = msg.getToIP();
		String s = msg.getContent();
		if (s.length() == 0 || s.equals(null)) {
			System.out.println("消息长度为0");
		} else if (toIP.length() == 0 || toIP.equals(null)) {
			System.out.println("目的地址为空");
		} else {
			this.validated = true;
		}
	}

	public boolean send() {
		if (validated) {
			try {
	
				ByteArrayOutputStream byteStream = new ByteArrayOutputStream(500);
				ObjectOutputStream os = new ObjectOutputStream(
						new BufferedOutputStream(byteStream));
				os.writeObject(msg);
				os.flush();
				byte[] data = byteStream.toByteArray();
	
				InetAddress destAddr = InetAddress.getByName(msg.getToIP());
				DatagramSocket theSocket = new DatagramSocket();
				DatagramPacket dp = new DatagramPacket(data, data.length, destAddr,
						Integer.parseInt(constants.CurrentConfigConstants.CLIENT_CURRENT_PORT));
				theSocket.send(dp);
				theSocket.close();
			} // end try
			catch (UnknownHostException uhex) {
				uhex.printStackTrace();
			} catch (SocketException sex) {
				sex.printStackTrace();
			} catch (IOException ioex) {
				ioex.printStackTrace();
			} // end catch
			return true;
		} else {
			return false;
		}
	}
}
